package com.dongdongshop.mq;

import com.dongdongshop.service.SMSService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component //说明是消费者
@RocketMQMessageListener(topic = "dk2208-topic", consumerGroup = "dk2208-consumer")
@Slf4j
public class MqConsumer implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private SMSService smsService;

    @Override
    public void onMessage(String s) {

    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list,//消息的集合
                                                            ConsumeConcurrentlyContext context) {
                for (MessageExt messageExt : list) {
                    String msgId = messageExt.getMsgId();//消息的id
                    log.info(msgId);
                    String topic = messageExt.getTopic();//消息的主题
                    log.info(topic);
                    String message = new String(messageExt.getBody());//消息的内容
                    log.info(message);
                    int reconsumeTimes = messageExt.getReconsumeTimes();//消息的重试次数
                    log.info(String.valueOf(reconsumeTimes));
                    try {
                        //消费成功后
                        smsService.sendPhoneMessage(message);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;//消费成功
                    } catch (Exception e) {
                        System.out.println("消息失败, 重试次数为" + reconsumeTimes);
                        //如果重试次数小于2
                        if (reconsumeTimes < 2) {
                            {
                                //返回给MQ的broker稍后重新消费
                                return ConsumeConcurrentlyStatus.RECONSUME_LATER;//消息失败
                            }
                        }
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;//返回成功
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
